<?php

namespace app\wechat\controller;

use app\wechat\controller\Openid;
use think\Db;
use think\facade\Log;
use think\Request;

class Index
{

    public $openPlatform;

    public function __construct()
    {
        $this->openPlatform = app('wechat.open_platform');
    }

    public function index()
    {
        $server = $this->openPlatform->server;
        return $server->serve();
    }

    public function callback(Request $request)
    {
        $info = $this->openPlatform->handleAuthorize();
        $appid = $info['authorization_info']['authorizer_appid'];
        $authtoken = $info['authorization_info']['authorizer_refresh_token'];
        $auth = $this->openPlatform->getAuthorizer($appid);
        $nick_name = $auth['authorizer_info']['nick_name'];
        $gh_id = $auth['authorizer_info']['user_name'];

        $data = ['name' => $nick_name, 'ghid' => $gh_id, 'appid' => $appid, 'refresh_token' => $authtoken];
        return Db::name('authorizers')->insert($data, true);
    }

    public function open_platform()
    {

        $url = $this->openPlatform->getPreAuthorizationUrl('http://wx.nanxuncn.cn/wechat/index/callback');

        return "<a href=" . $url. ">授权</a>";
    }

    // 获取授权链接
    public function get_preauth_url()
    {
        $url = $this->openPlatform->getPreAuthorizationUrl('http://wx.nanxuncn.cn/wechat/index/callback');
        return json($url);
    }

    public function get_authorizers($offset = 0, $count = 500)
    {
        $authorizers = $this->openPlatform->getAuthorizers($offset, $count);

        $list = $authorizers['list'];

        $res = array();

        foreach ($list as $item) {
            $a = $this->openPlatform->getAuthorizer($item['authorizer_appid']);
            $b['nick_name'] = $a['authorizer_info']['nick_name'];
            $b['gh_id'] = $a['authorizer_info']['user_name'];
            $b['appid'] = $item['authorizer_appid'];
            array_push($res, $b);
        }

        return json($res);
    }

    // 获取所有授权方列表
    public function get_authorizer_list()
    {
        $list = Db::table('authorizers')->select();
        return json($list);
    }

    // 模糊查询授权方公众号
    public function get_authorizer($keyword)
    {
        $acc = Db::table('authorizers')->where('id', 'like', '%' . $keyword . '%')->select();
        if (!$acc) {
            $acc = Db::table('authorizers')->where('name', 'like', '%' . $keyword . '%')->select();
            if (!$acc) {
                $acc = Db::table('authorizers')->where('ghid', 'like', '%' . $keyword . '%')->select();
            }
        }
        return json($acc);
    }
}
